from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.core.database.connection import get_database
from app.domains.alert.services import AlertService
from app.domains.alert.schemas import (
    AlertRuleCreate, AlertRuleUpdate, AlertRuleResponse, AlertRuleListQuery,
    AlertCreate, AlertUpdate, AlertResponse, AlertListQuery,
    NotificationChannelCreate, NotificationChannelUpdate, NotificationChannelResponse,
    AlertBatchOperation, TestAlertRequest, AlertStatistics
)
from app.shared.schemas.response import success_response, paginated_response, error_response
from app.shared.exceptions.base import ValidationException, BusinessException, NotFoundException
from app.shared.constants.status_codes import BusinessCode
from app.api.dependencies import get_current_user, require_roles, check_resource_permission, ResourcePermission
from app.shared.constants.enums import UserRole
import logging

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/alerts", tags=["告警管理"])


# ===== 告警规则管理 =====

@router.post("/rules", response_model=dict, summary="创建告警规则")
async def create_alert_rule(
    rule_data: AlertRuleCreate,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限创建告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    创建告警规则（管理员和经理可操作）
    
    - **rule_name**: 规则名称
    - **description**: 规则描述（可选）
    - **alert_type**: 告警类型
    - **level**: 告警级别
    - **is_enabled**: 是否启用
    - **condition_expression**: 条件表达式
    - **notification_template**: 通知模板（可选）
    - **notification_types**: 通知方式
    - **notification_recipients**: 通知接收人
    - **check_interval**: 检查间隔（秒）
    - **max_alert_frequency**: 最大告警频率（秒）
    - **device_types**: 适用设备类型（可选）
    - **locations**: 适用位置（可选）
    """
    try:
        alert_service = AlertService(db)
        rule = alert_service.create_alert_rule(rule_data, current_user['id'])
        
        logger.info(f"✅ 告警规则创建成功: {rule.rule_name} by {current_user['username']}")
        
        return success_response(
            data=AlertRuleResponse.from_orm(rule).dict(),
            message="告警规则创建成功"
        )
        
    except ValidationException as e:
        return error_response(
            message=str(e),
            code=BusinessCode.PARAM_ERROR
        )
    except Exception as e:
        logger.error(f"❌ 创建告警规则异常: {e}")
        return error_response(
            message="创建告警规则失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/rules", response_model=dict, summary="获取告警规则列表")
async def get_alert_rule_list(
    query: AlertRuleListQuery = Depends(),
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_view_alerts, "无权限查看告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    获取告警规则列表（管理员和经理可查看）
    
    - **page**: 页码（默认1）
    - **page_size**: 每页数量（默认20，最大100）
    - **search**: 搜索关键词（规则名称、描述）
    - **alert_type**: 告警类型筛选
    - **level**: 告警级别筛选
    - **is_enabled**: 是否启用筛选
    - **sort_by**: 排序字段（默认created_at）
    - **sort_order**: 排序方向（asc/desc，默认desc）
    """
    try:
        alert_service = AlertService(db)
        rules, total = alert_service.get_alert_rule_list(query)
        
        # 转换为响应格式
        rule_list = []
        for rule in rules:
            rule_dict = AlertRuleResponse.from_orm(rule).dict()
            # 添加创建人信息
            if rule.creator:
                rule_dict['created_by_name'] = rule.creator.username
            rule_list.append(rule_dict)
        
        return paginated_response(
            items=rule_list,
            total=total,
            page=query.page,
            page_size=query.page_size,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取告警规则列表异常: {e}")
        return error_response(
            message="获取告警规则列表失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/rules/{rule_id}", response_model=dict, summary="获取告警规则详情")
async def get_alert_rule_detail(
    rule_id: int,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_view_alerts, "无权限查看告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    获取告警规则详细信息
    """
    try:
        alert_service = AlertService(db)
        rule = alert_service.get_alert_rule_by_id(rule_id)
        
        rule_detail = AlertRuleResponse.from_orm(rule)
        
        # 添加创建人信息
        if rule.creator:
            rule_detail.created_by_name = rule.creator.username
        
        return success_response(
            data=rule_detail.dict(),
            message="查询成功"
        )
        
    except NotFoundException:
        return error_response(
            message="告警规则不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except Exception as e:
        logger.error(f"❌ 获取告警规则详情异常: {e}")
        return error_response(
            message="获取告警规则详情失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.put("/rules/{rule_id}", response_model=dict, summary="更新告警规则")
async def update_alert_rule(
    rule_id: int,
    rule_data: AlertRuleUpdate,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限修改告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    更新告警规则（管理员和经理可操作）
    """
    try:
        alert_service = AlertService(db)
        rule = alert_service.update_alert_rule(rule_id, rule_data)
        
        logger.info(f"✅ 告警规则更新成功: {rule.rule_name} by {current_user['username']}")
        
        return success_response(
            data=AlertRuleResponse.from_orm(rule).dict(),
            message="告警规则更新成功"
        )
        
    except NotFoundException:
        return error_response(
            message="告警规则不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except ValidationException as e:
        return error_response(
            message=str(e),
            code=BusinessCode.PARAM_ERROR
        )
    except Exception as e:
        logger.error(f"❌ 更新告警规则异常: {e}")
        return error_response(
            message="更新告警规则失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.delete("/rules/{rule_id}", response_model=dict, summary="删除告警规则")
async def delete_alert_rule(
    rule_id: int,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限删除告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    删除告警规则（管理员和经理可操作）
    
    注意：只能删除没有关联告警的规则
    """
    try:
        alert_service = AlertService(db)
        
        # 获取规则信息用于日志
        rule = alert_service.get_alert_rule_by_id(rule_id)
        
        success = alert_service.delete_alert_rule(rule_id)
        
        if success:
            logger.info(f"✅ 告警规则删除成功: {rule.rule_name} by {current_user['username']}")
            return success_response(message="告警规则删除成功")
        else:
            return error_response(
                message="告警规则删除失败",
                code=BusinessCode.OPERATION_FAILED
            )
        
    except NotFoundException:
        return error_response(
            message="告警规则不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except BusinessException as e:
        return error_response(
            message=str(e),
            code=e.code
        )
    except Exception as e:
        logger.error(f"❌ 删除告警规则异常: {e}")
        return error_response(
            message="删除告警规则失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.post("/rules/{rule_id}/test", response_model=dict, summary="测试告警规则")
async def test_alert_rule(
    rule_id: int,
    test_request: TestAlertRequest,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限测试告警规则"
    )),
    db: Session = Depends(get_database)
):
    """
    测试告警规则（管理员和经理可操作）
    
    - **test_data**: 测试数据（可选）
    """
    try:
        alert_service = AlertService(db)
        success = alert_service.test_alert_rule(test_request)
        
        if success:
            return success_response(message="告警规则测试通过")
        else:
            return error_response(
                message="告警规则测试失败",
                code=BusinessCode.OPERATION_FAILED
            )
        
    except NotFoundException:
        return error_response(
            message="告警规则不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except Exception as e:
        logger.error(f"❌ 测试告警规则异常: {e}")
        return error_response(
            message="测试告警规则失败",
            code=BusinessCode.OPERATION_FAILED
        )


# ===== 告警管理 =====

@router.post("", response_model=dict, summary="创建告警")
async def create_alert(
    alert_data: AlertCreate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    创建告警（系统自动或用户手动创建）
    
    - **title**: 告警标题
    - **content**: 告警内容
    - **level**: 告警级别
    - **alert_type**: 告警类型
    - **device_id**: 设备ID（可选）
    - **rule_id**: 告警规则ID（可选）
    - **source_data**: 源数据（可选）
    """
    try:
        alert_service = AlertService(db)
        alert = alert_service.create_alert(alert_data)
        
        logger.info(f"✅ 告警创建成功: {alert.alert_number} by {current_user['username']}")
        
        return success_response(
            data=AlertResponse.from_orm(alert).dict(),
            message="告警创建成功"
        )
        
    except ValidationException as e:
        return error_response(
            message=str(e),
            code=BusinessCode.PARAM_ERROR
        )
    except Exception as e:
        logger.error(f"❌ 创建告警异常: {e}")
        return error_response(
            message="创建告警失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("", response_model=dict, summary="获取告警列表")
async def get_alert_list(
    query: AlertListQuery = Depends(),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取告警列表（所有用户可查看）
    
    - **page**: 页码（默认1）
    - **page_size**: 每页数量（默认20，最大100）
    - **search**: 搜索关键词（告警编号、标题、设备编码）
    - **level**: 告警级别筛选
    - **alert_type**: 告警类型筛选
    - **device_id**: 设备ID筛选
    - **is_resolved**: 是否已解决筛选
    - **rule_id**: 告警规则ID筛选
    - **start_date**: 开始日期
    - **end_date**: 结束日期
    - **sort_by**: 排序字段（默认created_at）
    - **sort_order**: 排序方向（asc/desc，默认desc）
    """
    try:
        alert_service = AlertService(db)
        alerts, total = alert_service.get_alert_list(query)
        
        # 转换为响应格式
        alert_list = []
        for alert in alerts:
            alert_dict = AlertResponse.from_orm(alert).dict()
            # 添加关联信息
            if alert.device:
                alert_dict['device_code'] = alert.device.device_code
                alert_dict['device_name'] = alert.device.device_name
            if alert.rule:
                alert_dict['rule_name'] = alert.rule.rule_name
            if alert.resolver:
                alert_dict['resolved_by_name'] = alert.resolver.username
            alert_list.append(alert_dict)
        
        return paginated_response(
            items=alert_list,
            total=total,
            page=query.page,
            page_size=query.page_size,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取告警列表异常: {e}")
        return error_response(
            message="获取告警列表失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/{alert_id}", response_model=dict, summary="获取告警详情")
async def get_alert_detail(
    alert_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    获取告警详细信息
    """
    try:
        alert_service = AlertService(db)
        alert = alert_service.get_alert_by_id(alert_id)
        
        alert_detail = AlertResponse.from_orm(alert)
        
        # 添加关联信息
        if alert.device:
            alert_detail.device_code = alert.device.device_code
            alert_detail.device_name = alert.device.device_name
        if alert.rule:
            alert_detail.rule_name = alert.rule.rule_name
        if alert.resolver:
            alert_detail.resolved_by_name = alert.resolver.username
        
        return success_response(
            data=alert_detail.dict(),
            message="查询成功"
        )
        
    except NotFoundException:
        return error_response(
            message="告警不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except Exception as e:
        logger.error(f"❌ 获取告警详情异常: {e}")
        return error_response(
            message="获取告警详情失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.patch("/{alert_id}", response_model=dict, summary="更新告警")
async def update_alert(
    alert_id: int,
    alert_data: AlertUpdate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_database)
):
    """
    更新告警（技术员及以上可操作）
    
    - **is_resolved**: 是否已解决
    - **resolution_notes**: 解决备注
    """
    try:
        # 权限检查：技术员及以上可以解决告警
        if current_user['role'] == UserRole.USER.value:
            return error_response(
                message="无权限解决告警",
                code=BusinessCode.PERMISSION_DENIED
            )
        
        alert_service = AlertService(db)
        alert = alert_service.update_alert(alert_id, alert_data, current_user['id'])
        
        logger.info(f"✅ 告警更新成功: {alert.alert_number} by {current_user['username']}")
        
        return success_response(
            data=AlertResponse.from_orm(alert).dict(),
            message="告警更新成功"
        )
        
    except NotFoundException:
        return error_response(
            message="告警不存在",
            code=BusinessCode.DATA_NOT_FOUND
        )
    except Exception as e:
        logger.error(f"❌ 更新告警异常: {e}")
        return error_response(
            message="更新告警失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.post("/batch-operation", response_model=dict, summary="批量操作告警")
async def batch_operation(
    operation_data: AlertBatchOperation,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限批量操作告警"
    )),
    db: Session = Depends(get_database)
):
    """
    批量操作告警（经理和管理员可操作）
    
    - **alert_ids**: 告警ID列表
    - **operation**: 操作类型 (resolve, unresolve)
    - **params**: 操作参数
    
    支持的批量操作：
    - resolve: 批量解决 (params: {resolution_notes: str})
    - unresolve: 批量取消解决
    """
    try:
        alert_service = AlertService(db)
        results = alert_service.batch_operation(operation_data, current_user['id'])
        
        logger.info(
            f"✅ 批量操作完成: {operation_data.operation}, "
            f"成功 {len(results['success'])}, 失败 {len(results['failed'])} "
            f"by {current_user['username']}"
        )
        
        return success_response(
            data=results,
            message=f"批量操作完成，成功 {len(results['success'])} 个，失败 {len(results['failed'])} 个"
        )
        
    except ValidationException as e:
        return error_response(
            message=str(e),
            code=BusinessCode.PARAM_ERROR
        )
    except Exception as e:
        logger.error(f"❌ 批量操作异常: {e}")
        return error_response(
            message="批量操作失败",
            code=BusinessCode.OPERATION_FAILED
        )


@router.get("/statistics/dashboard", response_model=dict, summary="获取告警仪表盘统计")
async def get_dashboard_statistics(
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_view_reports, "无权限查看统计报表"
    )),
    db: Session = Depends(get_database)
):
    """
    获取告警仪表盘统计数据（经理和管理员可查看）
    """
    try:
        alert_service = AlertService(db)
        stats = alert_service.get_statistics()
        
        return success_response(
            data=stats,
            message="查询成功"
        )
        
    except Exception as e:
        logger.error(f"❌ 获取仪表盘统计异常: {e}")
        return error_response(
            message="获取统计数据失败",
            code=BusinessCode.OPERATION_FAILED
        )


# ===== 通知渠道管理 =====

@router.post("/notification-channels", response_model=dict, summary="创建通知渠道")
async def create_notification_channel(
    channel_data: NotificationChannelCreate,
    current_user: dict = Depends(check_resource_permission(
        ResourcePermission.can_manage_alerts, "无权限创建通知渠道"
    )),
    db: Session = Depends(get_database)
):
    """
    创建通知渠道（管理员可操作）
    
    - **channel_name**: 渠道名称
    - **channel_type**: 通知类型
    - **is_enabled**: 是否启用
    - **configuration**: 渠道配置
    """
    try:
        alert_service = AlertService(db)
        channel = alert_service.create_notification_channel(channel_data, current_user['id'])
        
        logger.info(f"✅ 通知渠道创建成功: {channel.channel_name} by {current_user['username']}")
        
        return success_response(
            data=NotificationChannelResponse.from_orm(channel).dict(),
            message="通知渠道创建成功"
        )
        
    except ValidationException as e:
        return error_response(
            message=str(e),
            code=BusinessCode.PARAM_ERROR
        )
    except Exception as e:
        logger.error(f"❌ 创建通知渠道异常: {e}")
        return error_response(
            message="创建通知渠道失败",
            code=BusinessCode.OPERATION_FAILED
        )